package com.lenovo.srl.dil.tiltbase.position_velocity.fragment;

import android.graphics.Point;
import android.view.View;

import com.lenovo.srl.dil.tiltbase.lib.fragment.BaseFragment;
import com.lenovo.srl.dil.tiltbase.lib.utils.PreferenceUtil;

public class PositionVelocityFragment extends BaseFragment {

	public PositionVelocityFragment() {
		mCtrlMode = CtrlMode.PostionVelocity;
	}

	@Override
	protected void moveDivier(float[] sensorData) {
		if (mPitchEnabled
				&& (sensorData[1] < -PreferenceUtil.get_move_up_init_angle() || sensorData[1] > PreferenceUtil
						.get_move_down_init_angle())) {
			if (mLastPitchTime == Long.MAX_VALUE) {
				mLastPitchTime = System.currentTimeMillis();
			} else {
				if (System.currentTimeMillis() - mLastPitchTime >= PreferenceUtil
						.get_move_up_down_time_delay()) {
					mLastPitchTime = Long.MAX_VALUE;
					mPitchEnabled = false;
					if (sensorData[1] > 0) {
						mDividerIndex += 1;
						if (mDividerIndex >= dividers.length) {
							mDividerIndex = dividers.length - 1;
						}
					} else {
						mDividerIndex -= 1;
						if (mDividerIndex < 0) {
							mDividerIndex = 0;
						}
					}
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							showDivider();
						}
					});
				}
			}
		} else if (sensorData[1] < -PreferenceUtil.get_move_up_init_angle()
				|| sensorData[1] > PreferenceUtil.get_move_down_init_angle()) {
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					mPitchEnabled = true;
					mLastPitchTime = Long.MAX_VALUE;
				}
			}, PreferenceUtil.get_move_up_down_time_delay());
		}
	}

	@Override
	protected double[] calcXYOffset(float[] sensorData, Point curBallPosition) {
		double tiltMag = Math.sqrt(sensorData[1] * sensorData[1]
				+ sensorData[2] * sensorData[2]);
		double tiltAngle = Math.asin(sensorData[2] / tiltMag) * 180 / Math.PI;
		int tiltGain = getTiltGainByTiltAngle(tiltAngle);
		double speed = tiltGain * Math.abs(tiltMag);
		double dBall = speed
				* (System.currentTimeMillis() - lastTimeStamp)
				/ 1000
				* getSpeedRatio(getInLayout(curBallPosition), curBallPosition.x);

		double[] result = new double[2];
		result[0] = dBall * Math.sin(tiltAngle * Math.PI / 180);
		result[1] = (sensorData[1] > 0 ? -1 : 1) * dBall
				* Math.cos(tiltAngle * Math.PI / 180);
		return result;
	}

	protected float getSpeedRatio(View overIcon, int x) {
		float ratio = PreferenceUtil.get_over_icon_speed_ratio();
		if (ratio > 1) {
			if (overIcon == null) {
				return 1f;
			}
			return PreferenceUtil.get_over_icon_min_speed_ratio()
					+ (1 - PreferenceUtil.get_over_icon_min_speed_ratio())
					* (float) Math
							.abs(Math.cos(x * Math.PI * 4 / SCREEN_WIDTH));
		} else if (overIcon == null) {
			return 1f;
		}
		return ratio;
	}
}
